<template>
	<div class="date-picker">
		<div class="date" @click="onStart">
			<p :class="{value: modelValue?.[0]}">{{ modelValue?.[0] || '开始时间' }}</p>
			<p>-</p>
			<p :class="{value: modelValue?.[1]}">{{ modelValue?.[1] || '结束时间' }}</p>
			<img
				v-if="clearable && modelValue?.length"
				@click.stop="onDelete"
				class="icon-delete"
				src="https://img.hzanchu.com/acimg/6cfcbbc91a02575685a796328d66a2a3.png"
				alt=""
			/>
		</div>

		<van-popup v-model:show="echoData.startVisible" position="bottom" round teleport="#app">
			<van-datetime-picker
				v-model="echoData.startValue"
				type="date"
				title="开始日期"
				:min-date="echoData.minDate"
				@cancel="echoData.startVisible = false"
				@confirm="onStartConfirm"
			/>
		</van-popup>

		<van-popup v-model:show="echoData.endVisible" position="bottom" round teleport="#app">
			<van-datetime-picker
				v-model="echoData.endValue"
				type="date"
				title="结束日期"
				:min-date="echoData.endMinDate"
				@cancel="echoData.endVisible = false"
				@confirm="onEndConfirm"
			/>
		</van-popup>

	</div>
</template>

<script setup>
import { defineEmits, defineProps, reactive, ref } from 'vue'
import { format } from 'date-fns'

defineProps({
	modelValue: {
		type: Array,
		default: () => []
	},
	clearable: {
		type: Boolean,
		default: true
	}
})

const emits = defineEmits(['update:modelValue'])

const echoData = reactive({
	startVisible: false,
	endVisible: false,
	startValue: new Date(),
	endValue: new Date(),
	minDate: new Date('2024-01-01'),
	endMinDate: new Date('2024-01-01'),
})

const onStart = () => {
	echoData.startVisible = true
}

const onDelete = () => {
	echoData.startValue = new Date()
	echoData.endMinDate = new Date()
	emits('update:modelValue', [])
}

const onStartConfirm = (e) => {
	echoData.startValue = new Date(e)
	echoData.startVisible = false
	echoData.endMinDate = new Date(e)
	echoData.endVisible = true
}

const onEndConfirm = e => {
	echoData.endVisible = false
	echoData.endValue = new Date(e)
	emits('update:modelValue', [
		format(echoData.startValue, 'yyyy-MM-dd'),
		format(echoData.endValue, 'yyyy-MM-dd'),
	])
}

</script>

<style scoped lang="less">
.date-picker {
	background: #fff;
	.date {
		display: flex;
		p {
			height: 92px;
			line-height: 92px;
			color: #BEBEBE;
			&:nth-of-type(1), &:nth-of-type(3) {
				flex: 1;
				text-align: center;
			}
		}
		.value {
			color: #333;
			font-size: 32px;
		}
		.icon-delete {
			width: 32px;
			height: 32px;
			margin: 28px 24px 0 0;
		}
	}
}
</style>
